package solution61;

/**
 * 61.Rotate List
 *
 * Given a list, rotate the list to the right by k places, where k is non-negative.
 * For example:
 * Given 1->2->3->4->5->NULL and k = 2,
 * return 4->5->1->2->3->NULL.
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head==null||head.next==null) return head;
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode fast=dummy,slow=dummy;

        int i;
        // 循环完后fast为最后一个结点
        for (i=0;fast.next!=null;i++)//Get the total length
            fast=fast.next;

        // 循环完后slow指向倒数第n+1个结点
        for (int j=i-n%i;j>0;j--) //Get the i-n%i th node
            slow=slow.next;

        // 连接原头结点
        fast.next=dummy.next; //Do the rotation
        // 头结点为倒数第n个结点
        dummy.next=slow.next;
        // 尾结点为null
        slow.next=null;

        return dummy.next;
    }
}
